<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { apiGet, apiPatch, apiPost } from '@/request/apiUtils';
import moment from 'moment';
import { ElMessage } from 'element-plus'
import CommonDialog from "@/components/CommonDialog.vue";

const formatDate = (d: any) => moment(d).format('YYYY-MM-DD');
const smoking_results_list: TObj = {
    1: '一次通过',
    2: '二次通过',
    3: '二次以上',
}
const if_extension_list: TObj = {
    1: '是',
    0: '否',
}
const initQuery = {
    demand_id: null,
    name: null,
    version: null,
    tester: null,
    test_date: null,
    launch_time: null,
    status: null,
};
const initForm = {
    id: null,
    demand_id: null,
    name: null,
    tester: null,
    demand_time: null,
    version: null,
    module: null,
    product: null,
    review_time: null,
    status: null,
    test_time: null,
    test_date: null,
    launch_time: null,
    smoking_results: null,
    if_extension: null,
    test_schedule: null,
    function_case_num: null,
    automation_case_num: null,
    key_words: null,
}
const { value: state } = ref({
    loading: false,
    tableData: [] as TObj[],
    total: 0,
    pageSize: 20,
    currentPage: 1,
    queryData: { ...initQuery },
    statistics: { demand_time_total: 0, test_time_total: 0 },
    maxtime: "",
    mintime: "",
    gantter_status: false,
    table_span: 24,
    gantt_span: 12,
    showDialog: false,
    isCreate: false,
    form: { ...initForm },
    dialogLoading: false,
});


const myBarList = ref([] as TObj[])
const startTime = ref([] as TObj[])
const endTime = ref([] as TObj[])

const fetchData = async (page = state.currentPage, size = state.pageSize) => {
    state.loading = true;
    try {
        const apiUrl = '/daily';
        const { test_date, launch_time } = state.queryData;
        const params: TObj = {
            page,
            size,
            ...state.queryData,
            ...test_date
                ? {
                    test_date_start: formatDate(test_date[0]),
                    test_date_end: formatDate(test_date[1]),
                }
                : {},
            ...launch_time
                ? {
                    launch_time_start: formatDate(launch_time[0]),
                    launch_time_end: formatDate(launch_time[1]),
                }
                : {},
        };
        delete params.test_date
        delete params.launch_time;
        const response: TObj = await apiGet(apiUrl, params); // 假设你有一个 API 端点返回数据
        state.tableData = response?.results || [];
        state.total = response?.count || 0;
        state.statistics.demand_time_total = response?.demand_time_total || 0;
        state.statistics.test_time_total = response?.test_time_total || 0;
        myBarList.value = []
        startTime.value = []
        endTime.value = []
        for (let i in state.tableData) {
            const bar = [{
                myBeginDate: state.tableData[i]['test_date'] + " 00:00",
                myEndDate: state.tableData[i]['launch_time'] + " 00:00",
                ganttBarConfig: {
                    id: state.tableData[i]['demand_id'],
                    label: state.tableData[i]['name']
                }
            }]
            if (state.tableData[i]['test_date'] != null) {
                startTime.value.push(state.tableData[i]['test_date'])
            }
            if (state.tableData[i]['launch_time'] != null) {
                endTime.value.push(state.tableData[i]['launch_time'])
            }
            myBarList.value.push(bar)
        }
        console.log('myBarList', myBarList)
        if (endTime.value.length != 0 && startTime.value.length != 0) {
            state.maxtime = endTime.value.sort()[endTime.value.length - 1] + " 00:00";
            state.mintime = startTime.value.sort()[0] + " 00:00";
        } else {
            state.maxtime = moment().add(5, 'days').format('YYYY-MM-DD') + " 00:00";
            state.mintime = moment().format('YYYY-MM-DD') + " 00:00";
        }
        console.log('state.mintime', state.mintime)
        console.log('state.maxtime', state.maxtime)

    } catch (error) {
        console.error('Error fetching data:', error);
    }
    state.loading = false;
};

// 页数改变
const handleSizeChange = (val: number) => {
    state.pageSize = val;
    fetchData(state.currentPage, val);
};
const handleCurrentChange = (val: number) => {
    state.currentPage = val;
    fetchData(val, state.pageSize);
};

// 重置
// const handleReset = () => {
//     console.log('initQuery', initQuery);
//     state.queryData = initQuery;
//     fetchData()
// };
// 查询
const handleSearch = () => {
    fetchData()
};

const hanleChangeGatter = () => {
    state.gantter_status = !state.gantter_status
    if (state.gantter_status) {
        state.table_span = 8;
        state.gantt_span = 16;
    } else {
        state.table_span = 24;
        state.gantt_span = 0;
    }
};

// 编辑
const handleEdit = (rowItem: TObj) => {
    state.showDialog = true;
    state.isCreate = false;
    const { id, demand_id, name, test_time, test_date, smoking_results, if_extension, test_schedule, function_case_num, automation_case_num } = rowItem || {};
    state.form = { id, demand_id, name, test_time, test_date, smoking_results, if_extension, test_schedule, function_case_num, automation_case_num };
}
// 新增
const handleCreate = () => {
    state.showDialog = true;
    state.isCreate = true;
    state.form = { ...initForm };
}
// 关闭弹窗
const handleClose = () => {
    state.showDialog = false;
    state.dialogLoading = false
}

// 弹窗确定
const handleConfirm = async () => {
    console.log('state.form', state.form)
    state.dialogLoading = true;
    try {
        if (state.isCreate) {
            const apiUrl = `/daily/`;
            await apiPost(apiUrl, state.form);
            ElMessage({
                message: '新增成功',
                type: 'success',
            })
        } else {
            const apiUrl = `/daily/${state.form.id}/`;
            await apiPatch(apiUrl, state.form);
            ElMessage({
                message: '修改成功',
                type: 'success',
            })
        }
        state.form = { ...initForm }
        state.showDialog = false
        fetchData(state.currentPage, state.pageSize);
    } catch (error) {
        console.error(error);
    }
    state.dialogLoading = false
}

onMounted(() => {
    fetchData();
});

</script>

<template class="home-wrap">
    <div class="home-search">
        <div class="home-search-inner">
            <el-input v-model="state.queryData.demand_id" placeholder="请输入ID" class="width200" />
            <el-input v-model="state.queryData.name" placeholder="请输入需求标题" class="width200" />
            <el-input v-model="state.queryData.version" placeholder="请输入项目" class="width200" />
            <el-input v-model="state.queryData.tester" placeholder="请输入测试人员" class="width200" />
            <el-input v-model="state.queryData.status" placeholder="请输入需求状态" class="width200" />
            <div class="date-wrap">
                <el-date-picker v-model="state.queryData.test_date" type="daterange" range-separator="-"
                    start-placeholder="提测日期开始" end-placeholder="提测日期结束" />
            </div>
            <div class="date-wrap">
                <el-date-picker v-model="state.queryData.launch_time" type="daterange" range-separator="-"
                    start-placeholder="上线日期开始" end-placeholder="上线日期结束" />
            </div>

            <!-- <el-button type="primary" @click="handleReset">重置</el-button> -->
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button type="success" @click="handleCreate">新增</el-button>
            <el-button type="warning" @click="hanleChangeGatter">甘特图开关</el-button>
        </div>
    </div>
    <div class="sta-wrap">
        统计：
        <span class="m-r-10">需求规模:{{ state.statistics.demand_time_total }}</span>
        <span>测试工时:{{ state.statistics.test_time_total }}</span>
    </div>
    <el-row>
        <el-col :span="state.table_span">
            <el-table :data="state.tableData" border style="width: 100%;" v-loading="state.loading"
                :header-cell-style="{ color: '#000', backgroundColor: '#61c5fc', height: '81px' }"
                :row-style="{ backgroundColor: '#cce4fa' }">
                <el-table-column prop="operate" label="操作" width="80" fixed="left">
                    <template v-slot="scope">
                        <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
                    </template>
                </el-table-column>
                <el-table-column prop="demand_id" label="ID" width="70" fixed="left" />
                <el-table-column prop="name" label="需求标题" width="400" fixed="left" show-overflow-tooltip="true" />
                <el-table-column prop="tester" label="测试人员" width="100" show-overflow-tooltip="true" fixed="left" />
                <el-table-column prop="demand_time" label="需求规模" width="90" />
                <el-table-column prop="version" label="项目" width="330" show-overflow-tooltip="true" />
                <el-table-column prop="module" label="模块" width="110" />
                <el-table-column prop="product" label="产品经理" width="100" />
                <el-table-column prop="review_time" label="评审时间" width="100" />
                <el-table-column prop="status" label="需求状态" width="100" />

                <el-table-column prop="test_time" label="测试工时" width="100" />
                <el-table-column prop="test_date" label="提测日期" width="100" />
                <el-table-column prop="launch_time" label="上线日期" width="100" />
                <el-table-column prop="smoking_results" label="冒烟结果" width="100">
                    <template v-slot="scope">
                        <span>{{ smoking_results_list?.[scope.row.smoking_results] || '-' }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="if_extension" label="提测是否延期" width="110">
                    <template v-slot="scope">
                        <span>{{ if_extension_list[scope.row.if_extension] || '-' }}</span>
                    </template>
                </el-table-column>

                <el-table-column prop="test_schedule" label="测试进度" width="100">
                     <template v-slot="scope">
                            <span>{{ scope.row.test_schedule ? scope.row.test_schedule + '%' : '-' }}</span>
                        </template>
                    </el-table-column>

                <el-table-column prop="function_case_num" label="功能用例数" width="100" />
                <el-table-column prop="automation_case_num" label="自动化用例数" width="112" />
                <el-table-column prop="key_words" label="关键字" width="399" show-overflow-tooltip="true" />
            </el-table>
        </el-col>
        <el-col :span="state.gantt_span" v-if="state.gantter_status">
            <g-gantt-chart :chart-start="state.mintime" :chart-end="state.maxtime" precision="day" row-height="40"
                width="100%" bar-start="myBeginDate" bar-end="myEndDate" grid="true" current-time="true">
                <g-gantt-row v-for="(bar, index) in myBarList" :key="index" :bars="bar" />
            </g-gantt-chart>
        </el-col>
    </el-row>

    <div class="example-pagination-block">
        <span class="m-r-5 font-12">共 {{ state.total }}</span>
        <el-pagination v-model:currentPage="state.currentPage" v-model:page-size="state.pageSize"
            :page-sizes="[20, 50, 100, 200]" :small="true" :disabled="false" :background="false"
            layout="sizes, prev, pager, next" :total="state.total" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
    </div>

    <el-dialog v-model="state.showDialog" :title="state.isCreate ? '新增' : '编辑'" width="40%" :before-close="handleClose">
        <el-form ref="form" :model="state.form" label-width="100px" v-loading="state.dialogLoading">
            <el-form-item label="ID">
                <el-input v-model="state.form.demand_id" :disabled="!state.isCreate"></el-input>
            </el-form-item>
            <el-form-item label="需求标题">
                <el-input v-model="state.form.name" :disabled="!state.isCreate"></el-input>
            </el-form-item>
            <el-form-item label="测试人员">
                <el-input v-model="state.form.tester"></el-input>
            </el-form-item>
            <el-form-item label="需求规模">
                <el-input-number :min="0" v-model="state.form.demand_time"></el-input-number>
            </el-form-item>
            <el-form-item label="项目">
                <el-input v-model="state.form.version"></el-input>
            </el-form-item>
            <el-form-item label="模块">
                <el-input v-model="state.form.module"></el-input>
            </el-form-item>
            <el-form-item label="产品经理">
                <el-input v-model="state.form.product"></el-input>
            </el-form-item>
            <el-form-item label="评审时间">
                <el-input v-model="state.form.review_time"></el-input>
            </el-form-item>
            <el-form-item label="需求状态">
                <el-input v-model="state.form.status"></el-input>
            </el-form-item>
            <el-form-item label="测试工时">
                <el-input-number :min="0" v-model="state.form.test_time"></el-input-number>
            </el-form-item>
            <el-form-item label="提测日期">
                <el-date-picker v-model="state.form.test_date" type="date" placeholder="请选择" format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD" />
            </el-form-item>
            <el-form-item label="上线日期">
                <el-date-picker v-model="state.form.launch_time" type="date" placeholder="请选择" format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD" />
            </el-form-item>
            <el-form-item label="冒烟结果">
                <el-select v-model="state.form.smoking_results" class="m-2" placeholder="请选择" size="large">
                    <el-option
                        v-for="item in Object.keys(smoking_results_list).map(item => ({ value: Number(item), label: smoking_results_list[item] }))"
                        :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="提测是否延期">
                <el-select v-model="state.form.if_extension" class="m-2" placeholder="请选择" size="large">
                    <el-option
                        v-for="item in Object.keys(if_extension_list).map(item => ({ value: Number(item), label: if_extension_list[item] }))"
                        :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="测试进度">
                <el-input-number :min="0" v-model="state.form.test_schedule"></el-input-number>
            </el-form-item>
            <el-form-item label="功能用例数">
                <el-input-number :min="0" v-model="state.form.function_case_num"></el-input-number>
            </el-form-item>
            <el-form-item label="自动化用例数">
                <el-input-number :min="0" v-model="state.form.automation_case_num"></el-input-number>
            </el-form-item>
            <el-form-item label="关键字">
                <el-input v-model="state.form.key_words"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="state.showDialog = false">取消</el-button>
                <el-button type="primary" @click="handleConfirm" :loading="state.dialogLoading">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<style scoped>
.home-wrap {
    position: relative;
}

.home-search {
    height: 80px;
}

.sta-wrap {
    display: flex;
    height: 20px;
    align-items: center;
    color: blue;
    font-size: 14px;
}

.home-search-inner {
    display: flex;
    flex-wrap: wrap;
    align-items: flex-start;
    gap: 10px;
}

.home-table {
    height: calc(100vh - 210px);
}

.example-pagination-block {
    display: flex;
    height: 40px;
    align-items: center;
    justify-content: end;
}
</style>
